package com.example.employeemanagement.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

/**
 * 数据初始化组件
 * 用于在应用启动时执行SQL脚本初始化数据
 */
@Component
public class DataInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 检查部门表是否有数据
        int count = jdbcTemplate.queryForObject("SELECT COUNT(*) FROM department", Integer.class);
        
        // 如果没有数据，则执行初始化脚本
        if (count == 0) {
            System.out.println("初始化部门数据...");
            executeSqlScript("sql/init.sql");
            System.out.println("部门数据初始化完成");
        } else {
            System.out.println("部门表已有数据，跳过初始化");
        }
    }

    /**
     * 执行SQL脚本文件
     * @param scriptPath 脚本路径
     * @throws IOException 如果读取脚本文件失败
     */
    private void executeSqlScript(String scriptPath) throws IOException {
        Resource resource = new ClassPathResource(scriptPath);
        Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
        String sql = FileCopyUtils.copyToString(reader);
        
        // 分割SQL语句并执行
        String[] sqlStatements = sql.split(";");
        for (String statement : sqlStatements) {
            if (!statement.trim().isEmpty()) {
                jdbcTemplate.execute(statement);
            }
        }
    }
}